package com.sgcc.activiti.service.impl;

import com.sgcc.activiti.domain.ExceptionMonitoringDto;
import com.sgcc.activiti.domain.OAnomalyInfo;
import com.sgcc.activiti.domain.OMonTar;
import com.sgcc.activiti.domain.vo.TotalFailuresNumberDto;
import com.sgcc.activiti.mapper.OAnomalyInfoMapper;
import com.sgcc.activiti.mapper.OMonTarMapper;
import com.sgcc.activiti.service.IOAnomalyInfoService;
import com.sgcc.activiti.service.IProcessService;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.core.utils.ServletUtils;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.datascope.annotation.DataScope;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.system.api.RemoteDeptService;
import com.sgcc.system.api.RemoteDistrictService;
import com.sgcc.system.api.domain.SysDept;
import com.sgcc.system.api.domain.SysDistrict;
import com.sgcc.system.api.domain.SysRole;
import com.sgcc.system.api.model.LoginUser;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 监控系统异常Service业务层处理
 *
 * @author sgcc
 * @date 2021-03-22
 */
@Service
public class OAnomalyInfoServiceImpl implements IOAnomalyInfoService {
    @Autowired
    private OAnomalyInfoMapper oAnomalyInfoMapper;
    @Autowired
    private IProcessService processService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RemoteDistrictService remoteDistrictService;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private OMonTarMapper monTarMapper;


    /**
     * 查询监控系统异常
     *
     * @param id 监控系统异常ID
     * @return 监控系统异常
     */
    @Override
    public OAnomalyInfo selectOAnomalyInfoById(String id) {
        return oAnomalyInfoMapper.selectOAnomalyInfoById(id);
    }

    /**
     * 查询监控系统异常列表
     *
     * @param oAnomalyInfo 监控系统异常
     * @return 监控系统异常
     */
    @Override
    @DataScope(deptAlias = "sys_dept")
    public List<OAnomalyInfo> selectOAnomalyInfoList(OAnomalyInfo oAnomalyInfo) {
        List<OAnomalyInfo> list = oAnomalyInfoMapper.selectOAnomalyInfoList(oAnomalyInfo);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {


                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    /**
     * 新增监控系统异常
     *
     * @param oAnomalyInfo 监控系统异常
     * @return 结果
     */
    @Override
    public int insertOAnomalyInfo(OAnomalyInfo oAnomalyInfo) {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        if (null == oAnomalyInfo.getId()) {
            oAnomalyInfo.setId(id);
        }
        oAnomalyInfo.setCreateTime(DateUtils.getNowDate());


        try {

            return oAnomalyInfoMapper.insertOAnomalyInfo(oAnomalyInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 修改监控系统异常
     *
     * @param oAnomalyInfo 监控系统异常
     * @return 结果
     */
    @Override
    public int updateOAnomalyInfo(OAnomalyInfo oAnomalyInfo) {
        oAnomalyInfo.setUpdateTime(DateUtils.getNowDate());
        return oAnomalyInfoMapper.updateOAnomalyInfo(oAnomalyInfo);
    }

    /**
     * 批量删除监控系统异常
     *
     * @param ids 需要删除的监控系统异常ID
     * @return 结果
     */
    @Override
    public int deleteOAnomalyInfoByIds(String[] ids) {
        return oAnomalyInfoMapper.deleteOAnomalyInfoByIds(ids);
    }

    /**
     * 删除监控系统异常信息
     *
     * @param id 监控系统异常ID
     * @return 结果
     */
    @Override
    public int deleteOAnomalyInfoById(String id) {
        return oAnomalyInfoMapper.deleteOAnomalyInfoById(id);
    }

    @Override
    public OAnomalyInfo getCount() {
        OAnomalyInfo oAnomalyInfo = new OAnomalyInfo();
        LoginUser user = tokenService.getLoginUser(ServletUtils.getRequest());

        oAnomalyInfo.setAssignee(user.getUsername());

        oAnomalyInfo.setRoleKey(user.getRoles());
        return oAnomalyInfoMapper.getCount(oAnomalyInfo);
    }

    @Override
    @DataScope(deptAlias = "sys_dept")
    public List<OAnomalyInfo> selectOAnomalyInfoProcessList(OAnomalyInfo oAnomalyInfo) {
        LoginUser user = tokenService.getLoginUser(ServletUtils.getRequest());

        oAnomalyInfo.setAssignee(user.getUsername());
        Set<String> ids = new HashSet<String>();
        for (SysRole role : user.getSysUser().getRoles()) {
            ids.add(role.getRoleKey());
        }

        oAnomalyInfo.setRoleKey(ids);
        List<OAnomalyInfo> list = oAnomalyInfoMapper.selectOAnomalyInfoProcessList(oAnomalyInfo);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
//                    if(null==item.getProcessKey()) {
                    item.setType("todo");
//                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    @Override
    public int insertOAnomalyInfoProcess(OAnomalyInfo oAnomalyInfo) {
        // TODO Auto-generated method stub

        String id = UUID.randomUUID().toString().replaceAll("-", "");
        if (null == oAnomalyInfo.getId()) {
            oAnomalyInfo.setId(id);
        }
        oAnomalyInfo.setCreateTime(DateUtils.getNowDate());
        try {
            processService.submitApplyAdmin(oAnomalyInfo, "abnormal", "admin");
            return oAnomalyInfoMapper.insertOAnomalyInfo(oAnomalyInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public HashMap<String, Object> exceptionMonitoring(Map<String, Object> condition) {
        HashMap<String, Object> result = new HashMap();
        Date date = new Date();
        String statisticalTime = (String) condition.get("statisticalTime");
        if (StringUtils.isEmpty(statisticalTime)) {
            //当天
//            statisticalTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            //取前一天的数据
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
//            calendar.set(Calendar.HOUR_OF_DAY,-24);
            date = calendar.getTime();
            statisticalTime = dateFormat.format(calendar.getTime());
        }
//        statisticalTime = statisticalTime.substring(0, 8);
        condition.put("statisticalTime", statisticalTime);
        String orgNo = (String) condition.get("orgNo");
        LoginUser user = tokenService.getLoginUser(ServletUtils.getRequest());
        user.getSysUser().getDeptId();
        R<SysDept> resultR = remoteDeptService.getDeptById(user.getSysUser().getDeptId());
        SysDept sysDistrict = resultR.getData();
        if (StringUtils.isEmpty(orgNo)) {
//            User user = UserUtils.getUser();
//            Office userCompany = user.getCompany();
//            orgNo = userCompany.getCode();
            if (sysDistrict != null) {
                condition.put("orgNo", sysDistrict.getDeptId());
            }
        }
//        Office office = officeMapper.selectByTypeAndCode("1", orgNo);
//        String orgName = office.getName();
        //010101 预受理流程监控
        ExceptionMonitoringDto preliminaryAcceptance = new ExceptionMonitoringDto();
        preliminaryAcceptance.setOrgNo(orgNo);
        if (sysDistrict != null) {
            preliminaryAcceptance.setOrgName(sysDistrict.getDeptName());
        }
        preliminaryAcceptance.setMonPoint("预受理流程监控");
        preliminaryAcceptance.setMonStatusCode("01");
        preliminaryAcceptance.setMonStatus("正常");
        preliminaryAcceptance.setMonTarCode("010101");
        preliminaryAcceptance.setOccTime(DateUtils.formatDate(date, "yyyy-MM-dd HH:mm"));
        condition.put("monTarCode", "010101");
        OMonTar oMonTar = monTarMapper.selectOMonTarByCode("010101");
        if (oMonTar != null && !"01".equals(oMonTar.getMonStatus())) {
            List<ExceptionMonitoringDto> datas1 = oAnomalyInfoMapper.exceptionMonitoring(condition);
            if (datas1.size() == 0 || null == datas1.get(0) || StringUtils.isEmpty(datas1.get(0).getMonTarCode())) {
                condition.put("orgNo", null);
                datas1 = oAnomalyInfoMapper.exceptionMonitoring(condition);
            }
            if (datas1.size() > 0 && null != datas1.get(0)) {
                ExceptionMonitoringDto monitoringDto = datas1.get(0);
                String monStatusCode = monitoringDto.getMonStatusCode();
                if (StringUtils.isNotEmpty(monStatusCode)) {
//                preliminaryAcceptance.setMonPoint(monitoringDto.getMonPoint());
                    preliminaryAcceptance.setMonStatusCode(monitoringDto.getMonStatusCode());
                    preliminaryAcceptance.setMonStatus(monitoringDto.getMonStatus());
                    preliminaryAcceptance.setMonMessage(monitoringDto.getMonMessage());
                    preliminaryAcceptance.setOccTime(monitoringDto.getOccTime());
//                preliminaryAcceptance.setMonTarCode(monitoringDto.getMonTarCode());
                    String no = monitoringDto.getOrgNo();
                    if (StringUtils.isNotEmpty(no)) {
                        R<SysDept> resultc = remoteDeptService.getDeptById(no);
                        SysDept district = resultc.getData();
                        if (null != district) {
                            preliminaryAcceptance.setOrgNo(no);
                            preliminaryAcceptance.setOrgName(district.getDeptName());
                        }
                    }
                }
            }
        }

        result.put("preliminaryAcceptance", preliminaryAcceptance);
        //010115 对账文本处理监控
        ExceptionMonitoringDto accountChecking = new ExceptionMonitoringDto();
        accountChecking.setOrgNo(orgNo);
        if (sysDistrict != null) {
            accountChecking.setOrgName(sysDistrict.getDeptName());
        }
        accountChecking.setMonPoint("对账文本处理监控");
        accountChecking.setMonStatusCode("01");
        accountChecking.setMonStatus("正常");
        accountChecking.setMonTarCode("010115");
        accountChecking.setOccTime(DateUtils.formatDate(date, "yyyy-MM-dd HH:mm"));
        condition.put("monTarCode", "010115");
        condition.put("orgNo", orgNo);


        OMonTar oMonTar2 = monTarMapper.selectOMonTarByCode("010115");
        if (oMonTar2 != null && !"01".equals(oMonTar2.getMonStatus())) {
            List<ExceptionMonitoringDto> datas2 = oAnomalyInfoMapper.exceptionMonitoring(condition);
            if (datas2.size() == 0 || null == datas2.get(0) || StringUtils.isEmpty(datas2.get(0).getMonTarCode())) {
                condition.put("orgNo", null);
                datas2 = oAnomalyInfoMapper.exceptionMonitoring(condition);
            }
            if (datas2.size() > 0 && null != datas2.get(0)) {
                ExceptionMonitoringDto monitoringDto = datas2.get(0);
                String monStatusCode = monitoringDto.getMonStatusCode();
                if (StringUtils.isNotEmpty(monStatusCode)) {
//                accountChecking.setMonPoint(monitoringDto.getMonPoint());
                    accountChecking.setMonStatusCode(monitoringDto.getMonStatusCode());
                    accountChecking.setMonStatus(monitoringDto.getMonStatus());
                    accountChecking.setMonMessage(monitoringDto.getMonMessage());
                    accountChecking.setOccTime(monitoringDto.getOccTime());
//                accountChecking.setMonTarCode(monitoringDto.getMonTarCode());
                    String no = monitoringDto.getOrgNo();
                    if (StringUtils.isNotEmpty(no)) {
                        R<SysDept> resultc = remoteDeptService.getDeptById(no);
                        SysDept district = resultc.getData();
                        if (null != district) {
                            accountChecking.setOrgNo(no);
                            accountChecking.setOrgName(district.getDeptName());
                        }
                    }
                }
            }
        }

        result.put("accountChecking", accountChecking);
//        result.add(preliminaryAcceptance);
//        result.add(accountChecking);
        return result;

    }


    @Override
    public List<TotalFailuresNumberDto> totalFailuresNumber(Map<String, Object> condition) {
        List<TotalFailuresNumberDto> result = new ArrayList<>();
        String statisticalTime = (String) condition.get("statisticalTime");
        if (StringUtils.isEmpty(statisticalTime)) {
            statisticalTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        }
        statisticalTime = statisticalTime.substring(0, 10);
        condition.put("statisticalTime", statisticalTime);
        String orgNo = (String) condition.get("orgNo");
        if (StringUtils.isEmpty(orgNo)) {
            orgNo = tokenService.getLoginUser().getSysUser().getDeptId();
            condition.put("orgNo", orgNo);
        }
        String type = (String) condition.get("type");
        if (StringUtils.isEmpty(type)) {
            type = "1";
        }

        if ("1".equals(type)) {
            //1.下载
            String[] donwloadMonTarCode = {"010801", "010802", "010803", "010804", "010805", "010806"};
            String[] donwloadMonTarName = {"抄表功能监控", "高压业务勘察", "低压业务勘察", "高压竣工验收", "停电监测", "专项检查"};
            for (int i = 0; i < donwloadMonTarCode.length; i++) {
                TotalFailuresNumberDto item = new TotalFailuresNumberDto(donwloadMonTarCode[i], donwloadMonTarName[i]);
                condition.put("monTarCode", donwloadMonTarCode[i]);
                List<TotalFailuresNumberDto> datas = oAnomalyInfoMapper.totalFailuresNumber(condition);
                if (datas != null && datas.size() > 0 && null != datas.get(0)) {
                    TotalFailuresNumberDto data = datas.get(0);
                    item.setTotalNum(data.getTotalNum());
                    item.setFailureNum(data.getFailureNum());
                }
                result.add(item);
            }
        } else if ("2".equals(type)) {
            //2.上传
            String[] uploadMonTarCode = {"010808", "010809", "010810", "010811", "010812"};
            String[] uploadMonTarName = {"抄表功能监控", "高压业务勘察", "低压业务勘察", "高压竣工验收", "缺陷登记"};
            for (int i = 0; i < uploadMonTarCode.length; i++) {
                TotalFailuresNumberDto item = new TotalFailuresNumberDto(uploadMonTarCode[i], uploadMonTarName[i]);
                condition.put("monTarCode", uploadMonTarCode[i]);
                List<TotalFailuresNumberDto> datas = oAnomalyInfoMapper.totalFailuresNumber(condition);
                if (datas != null && datas.size() > 0 && null != datas.get(0)) {
                    TotalFailuresNumberDto data = datas.get(0);
                    item.setTotalNum(data.getTotalNum());
                    item.setFailureNum(data.getFailureNum());
                }
                result.add(item);
            }
        }
        return result;
    }

    @Override
    public List<OAnomalyInfo> getExceptionDetailsList(OAnomalyInfo oAnomalyInfo) {
        String companyId = tokenService.getLoginUser().getSysUser().getDeptId(); //获取当前登录人单位id
        oAnomalyInfo.setOrgNo(companyId);
        return oAnomalyInfoMapper.getExceptionDetailsList(oAnomalyInfo);
    }
}
